import React, {Component} from 'react';
import axios from "axios"
import {connect} from "react-redux"


class Home extends Component {
	componentDidMount(){
		axios.get("data.json").then((res)=>{
			console.log(res.data)
			this.props.setShopList(res.data)
		})
	}
	render() {
		return (
			<div>
				<table className="table table-bordered">
					<thead>
					    <tr>
						    <th>id</th>
						    <th>名称</th>
						    <th>价格</th>
						    <th>数量</th>
						    <th>Actions</th>
					    </tr>
					</thead>
					<tbody>
					{
						this.props.shopList.map(item=>{
							return(
								<tr key={item.id}>
									<td>{item.id}</td>
									<td>{item.name}</td>
									<td>{item.price}</td>
									<td>
										{
											this.props.cartList.find(val=>val.id===item.id)?
											item.count:""
										}
										</td>
									<td>
										{
											this.props.cartList.find(val=>val.id===item.id)?
												<div>
													<button type="button" className="btn btn-info" onClick={()=>this.props.reduceCount(item.id)}>-</button>
													<button type="button" className="btn btn-warning" onClick={()=>this.props.addCount(item.id)}>+</button>
												</div>:
												<button type="button" className="btn btn-info"  onClick={()=>{this.props.add(item)}}>加入购物车</button>
										}

									</td>
								</tr>
							)
						})
					}
					</tbody>
				</table>
			</div>
		);
	}
}
function mapState(state) {
	return{
		shopList:state.shopList,
		cartList:state.cartList
	}
}
function mapAction(dispatch) {
	return{
		setShopList:(data)=>dispatch({
			type:"SET_SHOP_LIST",
			data
		}),
		add: item =>dispatch({
			type:"ADD",
			item
		}),
		addCount: id=>dispatch({
			type:"ADD_COUNT",
			id
		}),
		reduceCount:id=>dispatch({
			type:"REDUCE_COUNT",
			id
		})
	}
}
export default connect(mapState,mapAction)(Home);